package models

import (
	"bytes"
	"database/sql"
	"errors"
	"fmt"
	"log"
	"time"
)

type GroupModel struct {
	Id		int64`db:"id"`
	Name	string`db:"name"`
	CreateAt int64  `db:"create_at"`
	UpdateAt int64  `db:"update_at"`
}


func CreateGroup(db *sql.DB, name string, roles []int64) (bool, error) {
	tx,err := db.Begin()
	if err != nil {
		return false,err
	}
	sqlStr := "INSERT INTO `u_groups` (`name`,`create_at`,`update_at`) Values (?,?,?)"
	now := time.Now().Unix()
	res,err := tx.Exec(sqlStr,name,now,now)
	if err != nil {
		err := tx.Rollback()
		if err != nil {
			log.Printf("tx rollback err = %v\n",err)
		}
		return false,errors.New("create group error")
	}
	groupId,err :=res.LastInsertId()
	if err != nil {
		err := tx.Rollback()
		if err != nil {
			log.Printf("tx rollback err = %v\n",err)
		}
		return false,errors.New("create group error get insert id")
	}
	var buffer bytes.Buffer
	l := len(roles)
	for i,promiseId :=range roles {
		if i == l-1 {
			buffer.WriteString(fmt.Sprintf("('%d','%d');",groupId,promiseId))
		}else {
			buffer.WriteString(fmt.Sprintf("('%d','%d'),",groupId,promiseId))
		}
	}
	sqlStr = fmt.Sprintf("INSERT INTO `u_group_role` (`group_id`,`role_id`) VALUES %s",buffer.String())
	res,err = tx.Exec(sqlStr)
	if err != nil {
		err := tx.Rollback()
		if err != nil {
			log.Printf("tx rollback err = %v\n",err)
		}
		return false,errors.New("create group error insert role_promise")
	}
	rows,err := res.RowsAffected()
	if err != nil {
		err := tx.Rollback()
		if err != nil {
			log.Printf("tx rollback err = %v\n",err)
		}
		return false,errors.New("create group error")
	}
	if rows != int64(l) {
		err := tx.Rollback()
		if err != nil {
			log.Printf("tx rollback err = %v\n",err)
		}
		return false,errors.New("create group error row not ==")
	}
	err =tx.Commit()
	if err != nil {
		err := tx.Rollback()
		if err != nil {
			log.Printf("tx rollback err = %v\n",err)
		}
		return false,errors.New("create group error")
	}
	return true,nil
}